package com.eshop.modules.system.rest;

import java.lang.invoke.SerializedLambda;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.web.bind.annotation.DeleteMapping;
import com.eshop.modules.aop.ForbidSubmit;
import java.util.Iterator;
import java.util.Collection;
import cn.hutool.core.collection.CollectionUtil;
import java.util.ArrayList;
import java.util.Set;
import org.springframework.web.bind.annotation.PutMapping;
import com.eshop.utils.ValidationUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import org.springframework.web.bind.annotation.PostMapping;
import com.eshop.exception.BadRequestException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.validation.annotation.Validated;
import com.eshop.modules.system.domain.Dept;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import io.swagger.annotations.ApiOperation;
import com.eshop.logging.aop.log.Log;
import java.io.IOException;
import java.util.List;
import com.eshop.modules.system.service.dto.DeptDto;
import com.eshop.modules.system.service.dto.DeptQueryCriteria;
import javax.servlet.http.HttpServletResponse;
import com.eshop.dozer.service.IGenerator;
import com.eshop.config.DataScope;
import com.eshop.modules.system.service.DeptService;
import org.springframework.web.bind.annotation.RequestMapping;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Api(tags = { "系统：部门管理" })
@RequestMapping({ "/api/dept" })
public class DeptController
{
    private final DeptService deptService;
    private final DataScope dataScope;
    private final IGenerator generator;
    private static final String ENTITY_NAME = "dept";
    
    public DeptController(final DeptService deptService, final DataScope dataScope, final IGenerator generator) {
        this.deptService = deptService;
        this.dataScope = dataScope;
        this.generator = generator;
    }
    
    @Log("导出部门数据")
    @ApiOperation("导出部门数据")
    @GetMapping({ "/download" })
    @PreAuthorize("@el.check('admin','dept:list')")
    public void download(final HttpServletResponse response, final DeptQueryCriteria criteria) throws IOException {
        this.deptService.download(this.generator.convert((List)this.deptService.queryAll(criteria), (Class)DeptDto.class), response);
    }
    
    @Log("查询部门")
    @ApiOperation("查询部门")
    @GetMapping
    @PreAuthorize("@el.check('user:list','admin','dept:list')")
    public ResponseEntity<Object> getDepts(final DeptQueryCriteria criteria) {
        criteria.setIds(this.dataScope.getDeptIds());
        final List<DeptDto> deptDtos = (List<DeptDto>)this.generator.convert((List)this.deptService.queryAll(criteria), (Class)DeptDto.class);
        return new ResponseEntity(this.deptService.buildTree(deptDtos), HttpStatus.OK);
    }
    
    @Log("新增部门")
    @ApiOperation("新增部门")
    @PostMapping
    @PreAuthorize("@el.check('admin','dept:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody final Dept resources) {
        if (resources.getId() != null) {
            throw new BadRequestException("A new dept cannot already have an ID");
        }
        return new ResponseEntity(this.deptService.save(resources), HttpStatus.CREATED);
    }
    
    @Log("修改部门")
    @ApiOperation("修改部门")
    @PutMapping
    @PreAuthorize("@el.check('admin','dept:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody final Dept resources) {
        if (resources.getId().equals(resources.getPid())) {
            throw new BadRequestException("上级不能为自己");
        }
        final Dept dept = (Dept)this.deptService.getOne(Wrappers.<Dept>lambdaQuery().eq(Dept::getId, resources.getId()));
        ValidationUtil.isNull(dept.getId(), "Dept", "id", resources.getId());
        resources.setId(dept.getId());
        this.deptService.saveOrUpdate(resources);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }
    
    @ForbidSubmit
    @Log("删除部门")
    @ApiOperation("删除部门")
    @DeleteMapping
    @PreAuthorize("@el.check('admin','dept:del')")
    public ResponseEntity<Object> delete(@RequestBody final Set<Long> ids) {
        final List<Long> deptIds = new ArrayList<Long>();
        for (final Long id : ids) {
            final List<Dept> deptList = this.deptService.findByPid(id);
            final Dept dept = (Dept)this.deptService.getOne(Wrappers.<Dept>lambdaQuery().eq(Dept::getId, id));
            if (null != dept) {
                deptIds.add(dept.getId());
            }
            if (CollectionUtil.isNotEmpty((Collection)deptList)) {
                for (final Dept d : deptList) {
                    deptIds.add(d.getId());
                }
            }
        }
        this.deptService.delDepts(deptIds);
        return new ResponseEntity(HttpStatus.OK);
    }
}
